- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy paththread.cpp
48 lines (40 loc) · 1016 Bytes
/
thread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include"thread.h"
staticint g_tid = 0;
staticintfib(int n){
switch (n) {
case0: return1;
case1: return1;
default: return (fib(n-2) + fib(n-1));
}
}
void * thread_proc(void* ctx)
{
int tid = g_tid++;
char thread_name[16];
sprintf(thread_name, "Thread %d", tid);
#ifdef __APPLE__
pthread_setname_np(thread_name);
#else
pthread_setname_np(pthread_self(), thread_name);
#endif
// Random delay, 0 - 0.5 sec
timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 500000000 + ((float)rand() / (float)RAND_MAX) * 500000000;
nanosleep(&ts, NULL);
volatileint i = 0;
while (i <= 30) {
std::cout << "Thread " << tid << ": fib(" << i << ") = " << fib(i) << std::endl;
i++;
nanosleep(&ts, NULL);
}
std::cout << thread_name << " exited!" << std::endl;
}